<template>
  <div class="make-course-chapter-build">
    <div class="build-container">
      <div class="build-left">
        <div class="chapter-select">
          <!-- <span class="chapter-name">{{ chapterName }}</span> -->
          <el-select
            v-model="selectedChapter"
            placeholder="选择章节"
            @change="onChapterChange"
          >
            <el-option
              v-for="item in chapterOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-button type="primary" color="#155EEF" @click="testModel()"
            >预览页面效果</el-button
          >
        </div>

        <!-- 知识体系 -->
        <div class="section-container">
          <div class="section-header">
            <div class="section-title">知识体系</div>
            <div class="section-actions"></div>
          </div>
          <div class="section-content">
            <div
              class="knowledge-item"
              @click="toggleKnowledgeTree"
              @mouseenter="showEdit = true"
              @mouseleave="showEdit = false"
            >
              <div class="section-img">
                <img src="@/assets/img/知识体系-icon.png" alt="" />
              </div>
              <span class="item-text" @click.stop>知识点</span>
              <div class="tree-actions">
                <el-button
                  type="primary"
                  size="small"
                  color="#457AFF"
                  @click.stop="addKnowledgeNode()"
                >
                  新增
                </el-button>
                <!-- <el-button
                  type="primary"
                  size="small"
                  color="#457AFF"
                  @click.stop="saveKnowledgeTree()"
                >
                  保存
                </el-button> -->
              </div>
              <el-icon
                class="dropdown-icon"
                :class="{ rotate: showKnowledgeTree }"
              >
                <ArrowDown />
              </el-icon>
            </div>

            <!-- 下拉的知识树结构 -->
            <div v-show="showKnowledgeTree" class="knowledge-tree-container">
              <div class="tree-wrapper">
                <el-tree
                  :data="knowledgeTreeData"
                  node-key="id"
                  default-expand-all
                >
                  <template #default="{ node, data }">
                    <div
                      class="custom-tree-node"
                      @click.stop="handleNodeClick(data)"
                      @mouseenter="setHoverNodeId(data.id)"
                      @mouseleave="setHoverNodeId(null)"
                    >
                      <div class="tree-node-name">
                        <span>{{ data.name }}</span>
                      </div>
                      <div
                        class="tree-node-btn"
                        v-show="hoverNodeId === data.id"
                      >
                        <!-- <el-button
                          type="primary"
                          link
                          @click.stop="editKnowledgeNode(data)"
                        >
                          <el-icon><Edit /></el-icon>
                          编辑
                        </el-button> -->
                        <el-button
                          type="primary"
                          link
                          @click.stop="removeKnowledgeNode(node, data)"
                        >
                          <el-icon><Close /></el-icon>
                          删除
                        </el-button>
                      </div>
                    </div>
                  </template>
                </el-tree>
              </div>
            </div>
          </div>
        </div>

        <!-- 已同步知识库 -->
        <div class="section-container">
          <div class="section-header">
            <div class="section-title">已同步知识库</div>
            <div class="section-actions"></div>
          </div>
          <div class="section-content">
            <div
              v-for="item in knowledgeList"
              :key="item.id"
              class="resource-item"
              @mouseenter="showDel = true"
              @mouseleave="showDel = false"
            >
              <div class="section-img">
                <img src="@/assets/img/已同步知识库-icon.png" alt="" />
              </div>
              <span class="item-text" :title="item.name">{{ item.name }}</span>
            </div>
          </div>
        </div>

        <!-- 多模态资源库 -->
        <div
          class="section-container"
          v-if="duomotaiList && duomotaiList.length > 0"
        >
          <div class="section-header">
            <div class="section-title">多模态资源库</div>
            <div class="section-actions"></div>
          </div>
          <div class="section-content">
            <div
              v-for="item in duomotaiList"
              :key="item.id"
              class="resource-item"
              @mouseenter="showDel = true"
              @mouseleave="showDel = false"
            >
              <div class="section-img">
                <img src="@/assets/img/多模态资源库-icon.png" alt="" />
              </div>
              <span class="item-text" :title="item.name">{{ item.name }}</span>
              <!-- <span class="item-tag" v-show="showDel"
                ><el-icon><Close /></el-icon> 删除</span
              > -->
            </div>
          </div>
        </div>

        <!-- 课程题库 -->
        <div class="section-container">
          <div class="section-header">
            <div class="section-title">课程题库</div>
            <div class="section-actions"></div>
          </div>
          <div class="section-content">
            <div class="question-item">
              <div class="course-list-header">
                <div class="section-img">
                  <img src="@/assets/img/课程题库-icon.png" alt="" />
                </div>
                <span>课程题库列表</span>
              </div>
              <div class="course-info">
                <!-- <el-tooltip
                  content="选择:10道&nbsp;&nbsp;&nbsp;判断:10道&nbsp;&nbsp;&nbsp;简答:5道&nbsp;&nbsp;&nbsp;分析:5道"
                  placement="top"
                > -->
                <span class="courseNum">显示数量 {{ questionNum }}个</span>
                <!-- </el-tooltip> -->
                <span
                  class="detail-btn"
                  @click="
                    $router.push(
                      `/aiTeaching/courseBuild/makeCourseChapterBuildQuestion?id=${this.chapterId}&name=${this.chapterName}&selectedIds=${this.selectedQuestionIds}`
                    )
                  "
                  ><i class="iconfont icon-liebiao2"></i> 详情</span
                >
              </div>
            </div>
          </div>
        </div>

        <!-- 数字人设置 -->
        <div class="section-container">
          <div class="section-header">
            <div class="section-title">数字人设置</div>
            <div class="section-actions"></div>
          </div>
          <div class="section-content">
            <div
              class="shuziren-item"
              @mouseenter="showShuzirenEdit = true"
              @mouseleave="showShuzirenEdit = false"
            >
              <div class="course-list-header">
                <div class="section-img">
                  <img src="@/assets/img/数字人-icon.png" alt="" />
                </div>
                <span>{{
                  shuzirenDetail && shuzirenDetail.name
                    ? shuzirenDetail.name
                    : "未设置数字人"
                }}</span>
              </div>
              <div class="course-info" v-show="showShuzirenEdit">
                <span class="edit-btn" @click="editShuziren()"
                  ><el-icon><Edit /></el-icon> 修改</span
                >
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="build-right">
        <commonChat v-if="currentComponent === 'commonChat'" :id="chapterId" />
        <editKnowledge
          ref="editKnowledge"
          v-if="currentComponent === 'editKnowledge'"
          :nodeName="nodeName"
          :nodeKnowledge="nodeKnowledge"
          @saveKnowledge="saveKnowledge"
        />
        <editShuziren
          v-if="currentComponent === 'editShuziren'"
          :shuzirenList="shuzirenList"
          :shuzirenId="shuzirenId"
          @saveShuziren="saveShuziren"
        />
        <div class="no-data" v-if="!currentComponent">
          <img src="@/assets/img/no-data.png" alt="" />
          <span>暂无内容</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import commonChat from "@/components/commonChat.vue";
import editKnowledge from "@/components/editKnowledge.vue";
import editShuziren from "@/components/editShuziren.vue";
import { id } from "element-plus/es/locales.mjs";
export default {
  name: "make_courseChapterBuild",
  data() {
    return {
      courseId: "",
      chapterId: "",
      chapterName: "",
      showEdit: false,
      showDel: false,
      showShuzirenEdit: false,
      selectedChapter: "",
      chapterOptions: [], // 章节下拉
      duomotaiList: [], // 多模态资源库
      knowledgeList: [], // 已同步知识库
      currentComponent: "",
      showKnowledgeTree: false, // 控制知识树下拉显示
      hoverNodeId: null, // 鼠标悬停的节点ID
      knowledgeTreeData: [], // 知识点树
      editKnowledgeId: "", // 编辑知识节点id
      nodeName: "", // 节点名称
      nodeKnowledge: "", // 节点知识点
      shuzirenDetail: {}, // 数字人详情
      shuzirenList: [], // 数字人列表
      shuzirenId: "", // 数字人id
      questionNum: 0, // 题目数量
      selectedQuestionIds: [], // 已选中的题目id
    };
  },
  components: {
    commonChat,
    editKnowledge,
    editShuziren,
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.chapterId = this.$route.query.id;
    this.chapterName = this.$route.query.name;
    this.selectedChapter = Number(this.chapterId); // 设置默认选中的章节
    this.getChapterResource();
    this.getChapterList();
  },
  methods: {
    // 获取章节
    getChapterList() {
      this.$axios
        .get(`/tes/course/auto/make/all-chapter?courseId=${this.courseId}`)
        .then((res) => {
          this.chapterOptions = res.data;
        });
    },
    // 获取整体资源
    getChapterResource() {
      this.$axios
        .get(
          `/tes/course/auto/make/chapter-resource?courseId=${this.courseId}&chapterId=${this.chapterId}`
        )
        .then((res) => {
          this.duomotaiList = res.data.resources || [];
          this.knowledgeList = res.data.knowledge || [];
          this.knowledgeTreeData = res.data.knowledgeArray || [];
          this.shuzirenDetail = res.data.digitalHumen || {};
          this.shuzirenId = res.data.digitalHumen?.id || "";
          this.questionNum = res.data.questionRepository?.[0]?.num || 0;
          this.selectedQuestionIds =
            res.data.questionRepository?.[0]?.ids || [];
        });
    },

    // 获取数字人下拉
    getShuzirenSelect() {
      this.$axios.get(`/tes/digital-human/list?status=1`).then((res) => {
        this.shuzirenList = res.data;
      });
    },

    // 保存数字人
    saveShuziren(id) {
      this.$axios
        .post(`/tes/course/auto/make/chapter-resource`, {
          courseId: this.courseId,
          chapterId: Number(this.chapterId),
          type: 3,
          contextIds: [id],
        })
        .then((res) => {
          this.$message.success("保存成功");
          this.getChapterResource();
          this.currentComponent = "";
        });
    },

    // 修改知识点
    editKnowledgeBase() {
      this.$router.push(
        "/aiTeaching/courseBuild/makeCourseChapterBuildEditKnowledgeBase"
      );
    },

    // 修改数字人
    editShuziren() {
      this.currentComponent = "editShuziren";
      this.getShuzirenSelect();
    },

    // 切换知识树显示/隐藏
    toggleKnowledgeTree() {
      this.showKnowledgeTree = !this.showKnowledgeTree;
    },

    // 设置悬停节点ID
    setHoverNodeId(nodeId) {
      this.hoverNodeId = nodeId;
    },

    // 新增知识节点
    addKnowledgeNode() {
      this.editKnowledgeId = "";
      this.currentComponent = "editKnowledge";
      this.nodeName = "";
      this.nodeKnowledge = "";
    },

    // // 编辑知识节点
    // editKnowledgeNode(data) {
    //   this.idEditKnowledge = true;
    //   this.currentComponent = "editKnowledge";
    //   this.handleNodeClick(data);
    // },

    // 删除知识节点
    removeKnowledgeNode(node, data) {
      this.$confirm("确定删除该知识点吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .delete(
            `/tes/course/auto/make/chapter-kb?kbId=${data.id}&courseId=${this.courseId}&chapterId=${this.chapterId}`
          )
          .then((res) => {
            this.$message.success("删除成功");
            this.getChapterResource();
          });
      });
    },

    // 处理节点点击
    handleNodeClick(data) {
      this.editKnowledgeId = data.id;
      // 先清空数据，确保组件重新渲染时能正确接收新数据
      this.nodeName = "";
      this.nodeKnowledge = "";
      this.currentComponent = "";

      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      this.$axios
        .get(`/tes/graph/graph-relation-course-info/content?id=${data.id}`)
        .then((res) => {
          this.nodeName = data.name;
          this.nodeKnowledge = res.data;
          this.currentComponent = "editKnowledge";
          loading.close();
        });
    },

    // 保存知识点
    saveKnowledge(nodeName, nodeKnowledge) {
      let data = {};
      if (!this.editKnowledgeId) {
        data = {
          courseId: this.courseId,
          chapterId: this.chapterId,
          name: nodeName,
          content: nodeKnowledge,
        };
      } else {
        data = {
          courseId: this.courseId,
          chapterId: this.chapterId,
          name: nodeName,
          content: nodeKnowledge,
          id: this.editKnowledgeId,
        };
      }
      this.$axios.post(`/tes/course/auto/make/chapter-kb`, data).then((res) => {
        this.$message.success("保存成功");
        this.getChapterResource();
        this.currentComponent = "";
        this.editKnowledgeId = "";
      });
    },

    // 章节选择变化处理
    onChapterChange(chapterId) {
      this.chapterId = chapterId;
      // 从章节选项中找到对应的章节名称
      const selectedChapterOption = this.chapterOptions.find(
        (item) => item.id === chapterId
      );
      this.chapterName = selectedChapterOption
        ? selectedChapterOption.label
        : "";

      // 重新获取章节资源
      this.getChapterResource();

      // 清空右侧组件
      this.currentComponent = "";
    },

    // 测试模型
    testModel() {
      this.currentComponent = "commonChat";
    },
  },
};
</script>

<style lang="scss" scoped>
.make-course-chapter-build {
  background-color: #fff;
  box-sizing: border-box;
  overflow-x: hidden;
  height: calc(100vh - 270px);
  .build-container {
    display: flex;
    justify-content: center;
    width: 100%;
    height: 100%;

    .build-left {
      width: 52%;
      background: #fbfcff;
      padding: 20px;
      height: 100%;
      overflow-y: auto;
      box-sizing: border-box;
      &::-webkit-scrollbar {
        width: 5px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: #fbfcff;
        border-radius: 4px;
      }
      &::-webkit-scrollbar-track {
        background-color: #fbfcff;
      }
      .chapter-select {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
        margin-bottom: 20px;

        .el-select {
          width: 85%;
          margin-right: 10px;

          .el-input__inner {
            border-radius: 6px;
            height: 45px;
            font-size: 16px;
            font-weight: 500;
          }
        }
      }

      .section-container {
        border-radius: 6px;
        margin-bottom: 20px;

        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 15px 0;

          .section-title {
            font-size: 14px;
            font-weight: 500;
            color: #596184;
          }

          .section-actions {
            display: flex;
            align-items: center;

            i {
              cursor: pointer;
              color: #1890ff;
              font-size: 16px;

              &:hover {
                color: #40a9ff;
              }
            }
          }
        }

        .section-content {
          padding: 15px;
          border-bottom: 1px solid #dee4ef;
          .course-list-header {
            display: flex;
            align-items: center;
            .section-img {
              width: 20px;
              height: 20px;
              margin-right: 10px;
            }
          }
          .knowledge-item,
          .resource-item,
          .question-item,
          .shuziren-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            background-color: #f1f3f8;
            border-radius: 10px;
            margin-bottom: 8px;
            .tree-actions {
              display: flex;
              margin-right: 15px;
            }
            .section-img {
              width: 20px;
              height: 20px;
              margin-right: 10px;
              img {
                width: 100%;
              }
            }
            &:hover {
              background-color: #e8ecf7;
            }

            .item-text {
              flex: 1;
              font-size: 16px;
              color: #140e35;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .item-tag {
              font-size: 14px;
              display: flex;
              justify-content: center;
              align-items: center;
              color: #457aff;
              cursor: pointer;

              i {
                margin-right: 3px;
                margin-top: 2px;
              }
            }

            .dropdown-icon {
              margin-left: 8px;
              transition: transform 0.3s ease;
              color: #999;

              &.rotate {
                transform: rotate(180deg);
              }
            }

            .delete-icon {
              color: #ff4d4f;
              cursor: pointer;
            }
          }

          // 知识树下拉容器
          .knowledge-tree-container {
            border-radius: 6px;
            background: #e8ecf7;
            border: 1px solid #dee4ef;

            .tree-wrapper {
              padding: 16px;
              border-radius: 6px;
              max-height: 430px;
              overflow-y: auto;
              .el-tree {
                padding: 10px;
              }

              &::-webkit-scrollbar {
                width: 4px;
              }
              &::-webkit-scrollbar-thumb {
                background-color: #e8ecf7;
                border-radius: 2px;
              }
              &::-webkit-scrollbar-track {
                background-color: #ffffff;
              }

              .custom-tree-node {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 14px;
                padding-right: 8px;

                .tree-node-name {
                  display: flex;
                  align-items: center;

                  span {
                    color: #596184;
                    font-size: 13px;
                  }
                }

                // 默认隐藏删除按钮
                .tree-node-btn {
                  opacity: 0;
                  transition: opacity 0.2s ease-in-out;

                  .el-button {
                    color: #457aff;
                    font-size: 12px;
                    padding: 4px 8px;
                  }
                }

                // 鼠标悬停时显示删除按钮
                &:hover .tree-node-btn {
                  opacity: 1;
                }
              }
            }
          }

          .course-info {
            margin-left: auto;
            font-size: 12px;
            color: #999;

            .courseNum {
              color: #7582a3;
              font-size: 14px;
              cursor: pointer;
            }

            .detail-btn {
              margin-left: 15px;
              font-size: 14px;
              color: #457aff;
              cursor: pointer;
              i {
                margin-top: 2px;
              }
            }

            .edit-btn {
              display: flex;
              align-items: center;
              font-size: 14px;
              color: #457aff;
              cursor: pointer;
              .el-icon {
                margin-right: 3px;
              }
            }
          }
        }
      }
    }
    .build-right {
      width: 48%;
      .no-data {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        gap: 10px;
        span {
          font-size: 16px;
          color: #999;
        }
      }
    }
  }
}
</style>
